package com.apes.fico.masterdata.gl.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.fico.masterdata.gl.model.AccountingAuxiliaryProject;
import com.apes.fico.masterdata.gl.respository.AccountingAuxiliaryProjectRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName AccountingAuxiliaryProjectService
 * @Description TODO
 * @Author pengyb
 * @Date 2018/12/24 15:15
 * @Version 1.0
 **/
@Service("accountingAuxiliaryProjectService")
public class AccountingAuxiliaryProjectService extends DomainService {
    @Autowired
    private AccountingAuxiliaryProjectRepository accountingAuxiliaryProjectRepository;

    /**
     * 保存
     *
     * @param request
     * @return
     */
    public AccountingAuxiliaryProject save(SimpleRequest request) {
        AccountingAuxiliaryProject accountingAuxiliaryProject = request.getO(AccountingAuxiliaryProject.class);
        accountingAuxiliaryProject.setCreateDate(new Date());
        return accountingAuxiliaryProjectRepository.saveAndFlush(accountingAuxiliaryProject);
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
    public AccountingAuxiliaryProject update(SimpleRequest request) {
        checkData(request);
        AccountingAuxiliaryProject accountingAuxiliaryProject = request.getO(AccountingAuxiliaryProject.class);
        accountingAuxiliaryProject.setUpdateDate(new Date());
        return accountingAuxiliaryProjectRepository.saveAndFlush(accountingAuxiliaryProject);
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        checkData(request);
        AccountingAuxiliaryProject accountingAuxiliaryProject = request.getO(AccountingAuxiliaryProject.class);
        accountingAuxiliaryProjectRepository.delete(accountingAuxiliaryProject.getId());
        return "删除成功";
    }

    /**
     * 检查
     * @param request
     */
    public void checkData(SimpleRequest request) {
        AccountingAuxiliaryProject accountingAuxiliaryProject = accountingAuxiliaryProjectRepository.findOne((String) request.get("id"));
        if (accountingAuxiliaryProject == null) throw new RuntimeException(accountingAuxiliaryProject.getName() + "不存在");
        if (accountingAuxiliaryProject.getVersion()!=(int)request.get("version"))throw new RuntimeException(accountingAuxiliaryProject.getName() + "已更新或已删除");
    }

    /**
     * 下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<AccountingAuxiliaryProject> find(SimpleRequest request){
        return accountingAuxiliaryProjectRepository.find(request.get("key"),PageRequest.of(request.get("page"),request.get("size")));
    }
}
